//
//  GroupDetailVC.m
//  wanzhaoIM
//
//  Created by liuyuantao on 15/6/1.
//  Copyright (c) 2015年 liuyuantao. All rights reserved.
//

#import "GroupDetailVC.h"
//#import "CHSNavigationController.h"
//#import "CHSNavigationBar.h"
#import "MicroDef.h"
#import "CGroupInfoView.h"
#import "CGroupHeaderView.h"
//#import "Masonry.h"
#import "CGroupInfoBK.h"
#import "TextSwitchCell.h"
#import "SettingTextCell.h"
#import "JKAlertDialog.h"
#import "GroupNoticeVC.h"
#import "GroupFilesVC.h"
#import "GroupMenbersVC.h"
#import "CGroupMgr.h"
#import "IMChatRecordController.h"
#import "CXmppMgr.h"
#import "MessageSettingCell.h"
#import "CGroupMgr.h"
#import "CMessageMgr.h"
#import "CMessageModel.h"

#define KSECTIONHEIGHT 1.0f
@interface GroupDetailVC ()<UITableViewDelegate, UITableViewDataSource, UIGestureRecognizerDelegate ,TextSwitchCellDelegate, UIActionSheetDelegate>
{
    UITableView *_tableView;
    CGroupInfoView *_groupNotice;
    CGroupInfoView *_groupFile;
    CGroupInfoView *_groupMembers;
    CGroupInfoBK *_CGroupInfoBK;
    CGroupHeaderView *_headerView;
    CGroupMgr *_groupMgr;
    CMessageMgr *_messageMgr;
    NSArray *_messageArray;
}
@end

@implementation GroupDetailVC

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:K_XMPPUPDATEGROUPINFO object:nil];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
    // Do any additional setup after loading the view.
    [self.navigationController setNavigationBarHidden:NO];
    [self.navigationItem setHidesBackButton:YES];
    
    _groupMgr = [[CGroupMgr alloc] init];
    self.group = [_groupMgr loadGroup:self.group.GroupId];
    _messageMgr = [[CMessageMgr alloc] init];
    
    
    if (self.group.GroupName.length > 0) {
        [self.navigationItem setNewTitleCenter:self.group.GroupName];
    } else {
    
        [self.navigationItem setNewTitleCenter:@"群资料"];
    }
//    [(CHSNavigationBar *)self.navigationController.navigationBar setBackgroundImage];
//    [self.navigationItem setLeftItemWithTarget:self action:@selector(back) image:@"nvaBackIcon" selectedImageName:@"nvaBackIcon"  text:nil disabled:nil];

    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateGroup) name:K_XMPPUPDATEGROUPINFO object:nil];
    
    UIView *superview = self.view;
    NSArray *nib = [[NSBundle mainBundle]loadNibNamed:@"CGroupHeaderView" owner:self options:nil];
    CGroupHeaderView *headerview = [nib objectAtIndex:0];
//    [headerview set]
    [headerview.icon setImage:[UIImage imageNamed:@"110-110"]];
    [headerview.groupName setText:self.group.GroupName];
    NSString *groupMembersNum = [NSString stringWithFormat:@"%zd",self.group.UserNum];
    NSString *showText = [NSString stringWithFormat:@"%@人", groupMembersNum];
    [headerview.groupMemberNum setText:showText];
    [superview addSubview:headerview];
    _headerView = headerview;

    NSArray *nib1 = [[NSBundle mainBundle]loadNibNamed:@"CGroupInfoBK" owner:self options:nil];
    CGroupInfoBK *CGroupInfoBK = [nib1 objectAtIndex:0];
    _CGroupInfoBK = CGroupInfoBK;
    [superview addSubview:CGroupInfoBK];
    CGroupInfoBK.userInteractionEnabled = YES;
    
    NSArray *nib2 = [[NSBundle mainBundle]loadNibNamed:@"CGroupInfoView" owner:self options:nil];
     _groupNotice = [nib2 objectAtIndex:0];
    _groupNotice.backgroundColor = ClearColor;
    [_groupNotice.icon setImage:[UIImage imageNamed:@"goupNotice"]];
    [_groupNotice.label setText:@"公告"];
    [CGroupInfoBK addSubview:_groupNotice];
    _groupNotice.userInteractionEnabled = YES;
    _groupNotice.icon.userInteractionEnabled = YES;
    _groupNotice.hongdianIcon.hidden = YES;
    UITapGestureRecognizer *panRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showGroupNoticeVC)];
    //    [groupNotice.icon addGestureRecognizer:panRecognizer];//关键语句，给self.view添加一个手势监测；
    [_groupNotice addGestureRecognizer:panRecognizer];
    panRecognizer.numberOfTapsRequired = 1;
    //    panRecognizer.maximumNumberOfTouches = 1;
    panRecognizer.delegate = self;


    
    
    NSArray *nib3 = [[NSBundle mainBundle]loadNibNamed:@"CGroupInfoView" owner:self options:nil];
    _groupFile = [nib3 objectAtIndex:0];
    
        
    [_groupFile.icon setImage:[UIImage imageNamed:@"groupFile"]];
    _groupFile.backgroundColor = ClearColor;
    [_groupFile.label setText:@"文件"];
    _groupFile.hongdianIcon.hidden = YES;
    [CGroupInfoBK addSubview:_groupFile];
    _groupFile.userInteractionEnabled = YES;
    UITapGestureRecognizer *panRecognizer1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showGroupFilesVC)];
    [_groupFile addGestureRecognizer:panRecognizer1];//关键语句，给self.view添加一个手势监测；
    panRecognizer1.numberOfTapsRequired = 1;
    
    NSArray *nib4 = [[NSBundle mainBundle]loadNibNamed:@"CGroupInfoView" owner:self options:nil];
    _groupMembers = [nib4 objectAtIndex:0];
     _groupMembers.backgroundColor = ClearColor;
    [_groupMembers.icon setImage:[UIImage imageNamed:@"groupMembers"]];
    [_groupMembers.label setText:@"群成员"];
    _groupMembers.hongdianIcon.hidden = YES;
    _groupMembers.userInteractionEnabled = YES;
    [CGroupInfoBK addSubview:_groupMembers];
    UITapGestureRecognizer *panRecognizer2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showGroupMembersVC)];
    [_groupMembers addGestureRecognizer:panRecognizer2];//关键语句，给self.view添加一个手势监测；
    panRecognizer2.numberOfTapsRequired = 1;
    
    _tableView = [[UITableView alloc] init];
    _tableView.frame = self.view.frame;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
//    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.scrollEnabled = NO;
    [self.view addSubview:_tableView];
    
   __block  CGFloat hhWidth = (self.view.frame.size.width - 155.0f) / 3.0;
    headerview.frame = CGRectMake(0, 0, HARDWARE_SCREEN_WIDTH, 75.0f);
    
    CGroupInfoBK.frame = CGRectMake(0, CGRectGetMaxY(headerview.frame) + 20.0f, HARDWARE_SCREEN_WIDTH, 102.0f);
    
    CGFloat padding1 = 35.0f;
    CGFloat padding2 = 42.5f;
    _groupNotice.frame = CGRectMake(padding1, 1.0f, hhWidth, 100.0f);
    
    _groupFile.frame = CGRectMake(CGRectGetMaxX(_groupNotice.frame) + padding2, 1.0f, hhWidth, 100.0f);
    
    _groupMembers.frame = CGRectMake(CGRectGetMaxX(_groupFile.frame) + padding2, 1.0f, hhWidth, 100.0f);
   
    
    _tableView.frame = CGRectMake(0, CGRectGetMaxY(CGroupInfoBK.frame) + 20.0f, HARDWARE_SCREEN_WIDTH, 102.0f);
        
    self.view.userInteractionEnabled = YES;
    self.view.backgroundColor = RGBCOLOR(0xf3, 0xf3, 0xf3);
//    self.view.backgroundColor = [UIColor clearColor];
}

- (void)updateGroup
{
    self.group = [_groupMgr loadGroup:self.group.GroupId];
    
    if (self.group.GroupName.length > 0) {
        [self.navigationItem setNewTitleCenter:self.group.GroupName];
    } else {
        
        [self.navigationItem setNewTitleCenter:@"群资料"];
    }
    
    [_headerView.groupName setText:self.group.GroupName];
    NSString *groupMembersNum = [NSString stringWithFormat:@"%zd",self.group.UserNum];
    NSString *showText = [NSString stringWithFormat:@"%@人", groupMembersNum];
    [_headerView.groupMemberNum setText:showText];

}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    _messageArray = [_messageMgr loadNoLookFileMessageWithGroupId:self.group.GroupId];
    if (_messageArray.count > 0) {
        _groupFile.hongdianIcon.hidden = NO;
    } else {
        _groupFile.hongdianIcon.hidden = YES;
    }
    if (_isHaveNewNotice) {
        _groupNotice.hongdianIcon.hidden = NO;
    }
    else
    {
        _groupNotice.hongdianIcon.hidden = YES;
    }
}
//-(void)back
//{
//    [self.navigationController popViewControllerAnimated:YES ];
//}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/







#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    NSInteger rows = 0;
    
    switch (section) {
        case 0:
            rows = 2;
            break;
        default:
            rows = 0;
            break;
    }
    return rows;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView              // Default is 1 if not implemented
{
    return 1;
}
// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"MessageSettingCell";
    static NSString *TextCellIdentifier = @"SettingTextCell";
    UITableViewCell *cell = nil;
    if(indexPath.row == 0)
    {
        //        SettingUserInfoCell.
        
        MessageSettingCell  *textSwtichCell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (textSwtichCell == nil) {
            textSwtichCell = [[[NSBundle mainBundle] loadNibNamed:@"MessgeSettingCell" owner:self options:nil] objectAtIndex:0];
        }
        [textSwtichCell.titleLabel setText:[self titleName:indexPath]];
        [textSwtichCell.seperatorLine setHidden:NO];
        if (self.group.messageSettingType == MESSAGESETTING_RECEVIEDANDREMIND) {
           textSwtichCell.subTitleLabel.text = @"接收并提示";
        } else if (self.group.messageSettingType == MESSAGESETTING_RECEVIEDNOTREMIND) {
            textSwtichCell.subTitleLabel.text = @"接收而不提示";
        } else {
            textSwtichCell.subTitleLabel.text = @"只显示未读消息数目";
        }
        
        cell = textSwtichCell;
    }
    else
    {
        SettingTextCell *textCell = [tableView dequeueReusableCellWithIdentifier:TextCellIdentifier];
        if (textCell == nil) {
            textCell = [[[NSBundle mainBundle] loadNibNamed:@"SettingTextCell" owner:self options:nil] objectAtIndex:0];
        }

        [textCell.seperatorLine setHidden:YES];
        [textCell.titleLabel setText:[self titleName:indexPath]];
        cell = textCell;
    }
    
    return cell;
}

-(NSString *)titleName:(NSIndexPath *)indexPath
{
    NSString *title = nil;
    
    switch (indexPath.section) {
        case 0:
        {
            switch (indexPath.row) {
                case 0:
                    title = @"消息设置";
                    break;
                case 1:
                    title = @"消息记录";
                    break;
                    
                default:
                    break;
            }
        }
            break;
    }
    return title;
}




#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    CGFloat height = 0;
    switch (section) {
        case 0:
            height = KSECTIONHEIGHT;
            break;
        default:
            break;
    }
    return height;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    CGFloat height = 0;
    switch (section) {
        case 0:
            height = KSECTIONHEIGHT;
            break;
        default:
            break;
    }
    return height;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section   // custom view for header. will be adjusted to default or specified header height
{
    UIView *headerView = nil;
    headerView = [[UIView alloc] init];
    headerView.frame = CGRectMake(0, 0, tableView.frame.size.width, KSECTIONHEIGHT);
//    headerView.backgroundColor = RGBCOLOR(0xf3, 0xf3, 0xf3);
//    [headerView setBackgroundColor:[UIColor redColor]];
//    UIView *beginLine = [[UIView alloc] init];
//    beginLine.frame = CGRectMake(0, 0, tableView.frame.size.width, 0.5);
//    [beginLine setBackgroundColor:KSEPERATORLINECOLOR];
//    [headerView addSubview:beginLine];
    
    UIView *endLine = [[UIView alloc] init];
    endLine.frame = CGRectMake(0, KSECTIONHEIGHT-0.5, tableView.frame.size.width, 0.5);
    [endLine setBackgroundColor:KSEPERATORLINECOLOR];
//    [endLine setBackgroundColor:[UIColor redColor]];
    [headerView addSubview:endLine];
    
    return headerView;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section   // custom view for footer. will be adjusted to default or specified footer height
{
    UIView *headerView = nil;
    headerView = [[UIView alloc] init];
    headerView.frame = CGRectMake(0, 0, tableView.frame.size.width, 2);
    headerView.backgroundColor = RGBCOLOR(0xf3, 0xf3, 0xf3);
    UIView *beginLine = [[UIView alloc] init];
    beginLine.frame = CGRectMake(0, 0, tableView.frame.size.width, 0.5);
    [beginLine setBackgroundColor:KSEPERATORLINECOLOR];
    [headerView addSubview:beginLine];
    return headerView;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height = 50.0f;
    
    if(indexPath.row == 0 && indexPath.section == 0)
    {
        height = 50.0f;
    }
    return height;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    switch (indexPath.section)
    {
        case 0:
        {
            switch (indexPath.row)
            {
                case 0:
                {
                    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles: self.group.messageSettingType ==  MESSAGESETTING_RECEVIEDANDREMIND ? @"接收并提示√":@"接收并提示", self.group.messageSettingType == MESSAGESETTING_RECEVIEDNOTREMIND ? @"接收而不提示√":@"接收而不提示", self.group.messageSettingType    == MESSAGESETTING_ONLYSHOWUNREADCOUNT ?@"只显示未读消息数目√":@"只显示未读消息数目", nil];
                    [sheet showInView:self.view];
                }
                    
                    break;
                case 1:
                {
                    [self chatRecord];
                }
                    break;
                default:
                    break;
            }
        }
            break;
        default:
            break;
    }
}

#pragma mark actionsheedelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0:
        {
            self.group.messageSettingType = MESSAGESETTING_RECEVIEDANDREMIND;
            [_groupMgr updateGroup:self.group];
            [_tableView reloadData];
        }
            break;
        case 1:
        {
            self.group.messageSettingType = MESSAGESETTING_RECEVIEDNOTREMIND;
            [_groupMgr updateGroup:self.group];
            [_tableView reloadData];

        }
            break;
        case 2:
        {
            self.group.messageSettingType = MESSAGESETTING_ONLYSHOWUNREADCOUNT;
            [_groupMgr updateGroup:self.group];
            [_tableView reloadData];

        }
            break;
        case 3:
        {
            
        }
            break;
        default:
            break;
    }
}
//#pragma mark textSwitchdelegate
//- (void)SwitchCellDidChangeSettingWithIndexPath:(NSIndexPath *)indexPath settingValue:(BOOL)settingValue
//{
//    CGroupMgr *mgr = [[CGroupMgr alloc] init];
//    self.group.messageSettingType = settingValue ? 1:0;
//    [mgr updateGroup:self.group];
//    [_tableView reloadData];
//}

#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer

{
    
    return YES;
    
}


-(void)chatRecord
{
    IMChatRecordController *vc = [[IMChatRecordController alloc] init];
    vc.group = self.group;
    vc.member = nil;
    [self.navigationController pushViewController:vc animated:YES];

}


-(void)showGroupNoticeVC
{
    GroupNoticeVC *groupNotice = [[GroupNoticeVC alloc] init];
    groupNotice.group = self.group;
    _isHaveNewNotice = NO;
//    CHSNavigationController *groupNoticeNav = [[CHSNavigationController alloc] initWithRootViewController:groupNotice];
    //    [self.navigationController presentViewController:messageSettingNav animated:YES completion:nil];
    [self.navigationController pushViewController:groupNotice animated:YES];

}

-(void)showGroupFilesVC
{
    [_messageMgr updateGroupFileLookStatusWithGroupId:self.group.GroupId array:_messageArray];
    [USER_DEFAULT setBool:NO forKey:ISSHOWCHATREDDOPT];
    GroupFilesVC *groupFiles = [[GroupFilesVC alloc] init];
    groupFiles.group = self.group;
//        CHSNavigationController *groupFilesNav = [[CHSNavigationController alloc] initWithRootViewController:groupFiles];
        //    [self.navigationController presentViewController:messageSettingNav animated:YES completion:nil];
        [self.navigationController pushViewController:groupFiles animated:YES];
//    NSString *str = [NSString stringWithFormat:@"%s", __FUNCTION__];
//    JKAlertDialog *alert = [[JKAlertDialog alloc]initWithTitle:@"提示" message:str];
//    [alert addButton:Button_OK withTitle:@"确定" handler:^(JKAlertDialogItem *item)
//     {
//         
//     }];
//    [alert show];
}


-(void)showGroupMembersVC
{
        GroupMenbersVC *groupMembers = [[GroupMenbersVC alloc] init];
    
//        CHSNavigationController *safePrivacySettingNav = [[CHSNavigationController alloc] initWithRootViewController:groupMembers];
        //    [self.navigationController presentViewController:messageSettingNav animated:YES completion:nil];
        groupMembers.group = self.group;
        [self.navigationController pushViewController:groupMembers animated:YES];
}


@end
